﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
using System;

namespace ServiceLayerManagement
{
    public class SerializeHelper
    {
        public static byte[] Serialize<T>(T t)  //序列化类转为字节数据
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, t);
                return ms.GetBuffer();
            }
        }

        public static T Deserialize<T>(byte[] bytes)//反序列化字节数组转为对象
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BinaryFormatter bf = new BinaryFormatter();
                return (T)bf.Deserialize(ms);
            }
        }

        public static T DeepCopy<T>(T tSource)
        {
            T tTarget;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter br = new BinaryFormatter();
                br.Serialize(ms, tSource);
                ms.Seek(0, SeekOrigin.Begin);
                tTarget = (T)br.Deserialize(ms);
            }
            return tTarget;
        }

        public static bool Serialize<T>(T t, string filePath)
        {
            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(fs, t);

                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }

        }
        public static T Deserialize<T>(string filePath)
        {
            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        public static T DESerializer<T>(string strXML) where T : class
        {
            try
            {
                using (StreamReader sr = new StreamReader(strXML, Encoding.UTF8))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
